using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Diagnostics;
using System.Drawing;

using System.Runtime.InteropServices;
using System.IO;
using System.Collections;
using System.Threading;

using System.Windows.Forms.VisualStyles;
namespace WinSSHMenu
{
    public class WinSSHMenu
    {
        private ContextMenuStrip serverMenu;
        private NotifyIcon TrayIcon;

        [STAThread]
        static void Main()
        {
            bool firstInstance = true;
            Mutex mutex =
                new Mutex(false, "Local\\WinSSHMenu", out firstInstance);

            // Only run out app if we werent already running.
            if (firstInstance)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                WinSSHMenu menu = new WinSSHMenu();
                Application.Run();
            }
            else
            {
                MessageBox.Show("A instance of the application is already " +   
                                "running.\nPlease exit that one before " +
                                "attempting to start another.\n\nmkay, " +
                                "thanks.");
            }

        }   

        public WinSSHMenu()
		{
			InitializeComponent();
		}

        /// <summary>
        /// Initialize our components
        /// </summary>
		private void InitializeComponent()
		{
            this.serverMenu = new System.Windows.Forms.ContextMenuStrip();
            this.TrayIcon = new System.Windows.Forms.NotifyIcon();

            // 
            // serverMenu
            // 
            this.serverMenu.Name = "serverMenu";
            this.serverMenu.Size = new System.Drawing.Size(61, 4);
            this.serverMenu.Opening += 
                new System.ComponentModel.CancelEventHandler(serverMenu_Opening);
            // 
            // TrayIcon
            // 
            this.TrayIcon.ContextMenuStrip = this.serverMenu;
            this.TrayIcon.Icon = Properties.Resources.AppIcon;

            this.TrayIcon.Text = "WinSSHMenu";
            this.TrayIcon.Visible = true;
            this.TrayIcon.Click += 
                new System.EventHandler(this.TrayIcon_Click);
            this.TrayIcon.DoubleClick += 
                new EventHandler(this.TrayIcon_DoubleClick);
		}

        /// <summary>
        /// Builds our menu by reading in the server list from the config file
        /// and builds a context menu.
        /// </summary>
        private void BuildMenu()
        {
            // Delete any items that already exist, so we can rebuild the menu
            if (serverMenu.Items.Count > 0)
            {
                serverMenu.Items.Clear();
            }
            // Add the servers
            MenuSerializer ms = new MenuSerializer();
            
            FileUtil util = new FileUtil();

            ms.DeserializeMenu(serverMenu, util.AppPath);
            ArrayList items = new ArrayList();
            ToolStripMenuItem rootNode = (ToolStripMenuItem)serverMenu.Items[0];
            foreach(ToolStripMenuItem item in rootNode.DropDown.Items)
            {
                items.Add(item);
            }

            serverMenu.Items.Clear();
            foreach (ToolStripMenuItem itemToAdd in items)
            {
                serverMenu.Items.Add((ToolStripMenuItem)itemToAdd);
            }

            // Finally add the properties menu item
            serverMenu.Items.Add(new ToolStripSeparator());
            
            ToolStripMenuItem menuProperties = new ToolStripMenuItem();
            menuProperties.Text = "Properties";
            menuProperties.Click +=
                new System.EventHandler(this.propertiesToolStripMenuItem_Click);
            serverMenu.Items.Add(menuProperties);

            ToolStripMenuItem aboutMenu = new ToolStripMenuItem();
            aboutMenu.Text = "About";
            aboutMenu.Click +=
                new System.EventHandler(aboutMenuToolStripItem_Click);
            serverMenu.Items.Add(aboutMenu);
            
            ToolStripMenuItem exitMenu = new ToolStripMenuItem();
            exitMenu.Text = "Exit";
            exitMenu.Click +=
                new System.EventHandler(this.exitMenuToolStripItem_Click);
            serverMenu.Items.Add(exitMenu);
            
        }

        public static void openAllWindows_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem item = (ToolStripMenuItem)sender;
            ToolStrip ParentItem = item.Owner;

            // Find out how many items we are about to open
            int windowCount = 0;
            int ItemCount = ParentItem.Items.Count - 2;

            for (int i = 0; i < ParentItem.Items.Count; i++)
            {
                if (ItemCount > Properties.Settings.Default.WindowAlertLimit)
                {
                    if (ParentItem.Items[i].Text.Equals("Open All Windows") ||
                        ParentItem.Items[i].Text.Equals(""))
                    {
                        continue;
                    }
                    windowCount++;
                }
            }

            FileUtil util = new FileUtil();
            if (windowCount > Properties.Settings.Default.WindowAlertLimit)
            {
                DialogResult dlgResult =
                    MessageBox.Show("You are about to open " +
                    windowCount + " items, are you sure you want " +
                    "to continue?", "Are you sure?",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dlgResult == DialogResult.Yes)
                {
                    util.LaunchSSHProcess(ParentItem.Items);
                    return;
                }
            }
            else
            {
                util.LaunchSSHProcess(ParentItem.Items);
            }
        }


        public static void itemToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LaunchSSHSession((ToolStripMenuItem)sender);
        }

        public static void LaunchSSHSession(ToolStripMenuItem ItemToLaunch)
        {
            ToolStripMenuItem item = (ToolStripMenuItem)ItemToLaunch;
            String arg = item.Tag.ToString();
            FileUtil util = new FileUtil();
            util.LaunchSSHProcess(arg, item.Text);
        }

        public static void aboutMenuToolStripItem_Click(object sender, 
                                                        EventArgs e)
        {
            WinSSHMenuPreferences propertiesForm = new WinSSHMenuPreferences();
            propertiesForm.prefTabs.SelectedTab = propertiesForm.prefTabs.TabPages[3];
            propertiesForm.Show();
        }

        private void propertiesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            WinSSHMenuPreferences propertiesForm = new WinSSHMenuPreferences();
            propertiesForm.Show();
        }

        private void exitMenuToolStripItem_Click(object sender, EventArgs e)
        {
            // make sure they really want to quit
            DialogResult dlgResult = 
                MessageBox.Show("Are you sure you want to exit?", "Exit?", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dlgResult == DialogResult.Yes)
            {
                TrayIcon.Dispose();
                Application.Exit();
            }
        }
     
        private void serverMenu_Opening(object sender, CancelEventArgs e)
        {

        }

        private void TrayIcon_Click(object sender, EventArgs e)
        {
            BuildMenu();
        }

        private void TrayIcon_DoubleClick(object sender, EventArgs e)
        {
            // Disabling it for now.  Too easy to trigger accidently
            //WinSSHMenuPreferences propertiesForm = new WinSSHMenuPreferences();
            //propertiesForm.Show();
        }

	}
}
